import Callout from 'components/Callout';
import {Tab, Tabs} from 'nextra-theme-docs';
import Details from 'components/Details';

# Navigation APIs

<Callout>
  The navigation APIs are only needed when you're using [i18n
  routing](/docs/getting-started/app-router).
</Callout>

`next-intl` provides drop-in replacements for common Next.js navigation APIs that automatically handle the user locale and pathnames behind the scenes.

Depending on if you're using localized pathnames (i.e. the [`pathnames`](/docs/routing#pathnames) setting), you can pick from one of these functions to create the corresponding navigation APIs:

- `createSharedPathnamesNavigation`: Pathnames are shared across all locales (default)
- `createLocalizedPathnamesNavigation`: Pathnames are provided per locale (use with `pathnames`)

These functions are typically called in a central module like `src/navigation.ts` in order to provide easy access to navigation APIs in your components and should receive configuration options that are [shared](/docs/routing#shared-configuration) with the middleware.

<Tabs storageKey="pathnames" items={['Shared pathnames', 'Localized pathnames']}>
<Tab>

```tsx filename="navigation.ts"
import {createSharedPathnamesNavigation} from 'next-intl/navigation';
import {locales, /* ... */} from './config';

export const {Link, redirect, usePathname, useRouter} =
  createSharedPathnamesNavigation({locales, /* ... */});
```

<Details id="locales-unknown">
<summary>What if the locales aren't known at build time?</summary>

In case you're building an app where locales can be added and removed at runtime, you can omit the `locales` argument from `createSharedPathnamesNavigation`. The `locale` that can be passed to APIs like `Link` will now accept any string as a valid value.

Note however that the `locales` argument for the middleware is mandatory. You can however [create the middleware dynamically](/docs/routing/middleware#composing-other-middlewares) on a per-request basis and provide the `locales` argument e.g. after fetching this from a database.

</Details>

</Tab>
<Tab>

```tsx filename="navigation.ts"
import {createLocalizedPathnamesNavigation} from 'next-intl/navigation';
import {locales, pathnames, /* ... */} from './config';

export const {Link, redirect, usePathname, useRouter, getPathname} =
  createLocalizedPathnamesNavigation({locales, pathnames, /* ... */});
```

<Callout>
  Have a look at the [App Router example](/examples#app-router) to explore a
  working implementation of localized pathnames.
</Callout>

</Tab>
</Tabs>

<Details id="lint-consistent-usage">
<summary>How can I ensure consistent usage of navigation APIs?</summary>

To ensure consistent usage in your app, you can consider [linting for usage of these APIs](/docs/workflows/linting#consistent-usage-of-navigation-apis).

</Details>

## APIs

### `Link`

This component wraps [`next/link`](https://nextjs.org/docs/app/api-reference/components/link) and automatically prefixes the `href` with the either the current locale or a locale the user is switching to as necessary.

<Tabs storageKey="pathnames" items={['Shared pathnames', 'Localized pathnames']}>
<Tab>

```tsx
import {Link} from '../navigation';

// When the user is on `/en`, the link will point to `/en/about`
<Link href="/about">About</Link>

// You can override the `locale` to switch to another language
<Link href="/" locale="de">Switch to German</Link>

// Dynamic params need to be interpolated into the pathname
<Link href="/users/12">Susan</Link>
```

If you're providing the `locale` prop, the `hreflang` attribute will be set accordingly on the anchor tag.

<Details id="link-active">
<summary>How can I render a navigation link?</summary>

The [`useSelectedLayoutSegment` hook](https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment) from Next.js allows you to detect if a given child segment is active from within the parent layout. Since this returns an internal pathname, it can be matched against an `href` that you can pass to `Link`.

```tsx filename="NavigationLink.tsx"
'use client';

import {useSelectedLayoutSegment} from 'next/navigation';
import {ComponentProps} from 'react';
import {Link} from '../navigation';

export default function NavigationLink({
  href,
  ...rest
}: ComponentProps<typeof Link>) {
  const selectedLayoutSegment = useSelectedLayoutSegment();
  const pathname = selectedLayoutSegment ? `/${selectedLayoutSegment}` : '/';
  const isActive = pathname === href;

  return (
    <Link
      aria-current={isActive ? 'page' : undefined}
      href={href}
      style={{fontWeight: isActive ? 'bold' : 'normal'}}
      {...rest}
    />
  );
}
```

```tsx filename="Navigation.tsx"
<nav>
  <NavigationLink href="/">{t('home')}</NavigationLink>
  <NavigationLink href="/about">{t('about')}</NavigationLink>
  <NavigationLink href="/blog">{t('blog')}</NavigationLink>
</nav>
```

See also the Next.js docs on [creating an active link component](https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment#creating-an-active-link-component).

</Details>

</Tab>
<Tab>
When using [localized pathnames](/docs/routing#pathnames), the `href` prop corresponds to an internal pathname, but will be mapped to a locale-specific pathname.

```tsx
import {Link} from '../navigation';

// When the user is on `/de`, the link will point to `/de/ueber-uns`
<Link href="/about">About</Link>

// You can override the `locale` to switch to another language
<Link href="/" locale="en">Switch to English</Link>

// Dynamic params can be passed via the object form
<Link href={{
  pathname: '/users/[userId]',
  params: {userId: '5'}
}}>
  Susan
</Link>

// Catch-all params can be passed as arrays
<Link href={{
  pathname: '/categories/[...slug]',
  params: {slug: ['clothing', 't-shirts']}
}}>
  T-Shirts
</Link>

// Search params can be added via `query`
<Link href={{pathname: "/users", query: {sortBy: 'name'}}}>Users</Link>
```

<Details id="link-composition">
<summary>How can I compose the link with its href prop?</summary>

If you need to create a component that receives an `href` prop that is forwarded to `Link` internally, you can retain the type safety of `href` by making your component generic and accepting a `Pathname`. The type argument can then be forwarded to the internal props of `Link`.

```tsx filename="StyledLink.tsx"
import {ComponentProps} from 'react';
import {Link, pathnames} from '../navigation';

export default function StyledLink<Pathname extends keyof typeof pathnames>({
  color,
  href,
  ...rest
}: {color: 'blue' | 'red'} & ComponentProps<typeof Link<Pathname>>) {
  return <Link href={href} style={{color}} {...rest} />;
}
```

</Details>

<Details id="navigation-link">
<summary>How can I render a navigation link?</summary>

The [`useSelectedLayoutSegment` hook](https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment) from Next.js allows you to detect if a given child segment is active from within the parent layout. Since this returns an internal pathname, it can be matched against an `href` that you can pass to `Link`.

To ensure that only valid pathnames can be passed to the component, we can accept a type argument to be forwarded to the wrapped `Link`.

```tsx filename="NavigationLink.tsx"
'use client';

import {useSelectedLayoutSegment} from 'next/navigation';
import {ComponentProps} from 'react';
import {Link, pathnames} from '../navigation';

export default function NavigationLink<
  Pathname extends keyof typeof pathnames
>({href, ...rest}: ComponentProps<typeof Link<Pathname>>) {
  const selectedLayoutSegment = useSelectedLayoutSegment();
  const pathname = selectedLayoutSegment ? `/${selectedLayoutSegment}` : '/';
  const isActive = pathname === href;

  return (
    <Link
      aria-current={isActive ? 'page' : undefined}
      href={href}
      style={{fontWeight: isActive ? 'bold' : 'normal'}}
      {...rest}
    />
  );
}
```

```tsx filename="Navigation.tsx"
<nav>
  <NavigationLink href="/">{t('home')}</NavigationLink>
  <NavigationLink href="/about">{t('about')}</NavigationLink>
  <NavigationLink href="/blog">{t('blog')}</NavigationLink>
</nav>
```

See also the Next.js docs on [creating an active link component](https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment#creating-an-active-link-component).

</Details>

<Details id="link-unknown-routes">
<summary>How can I link to unknown routes?</summary>

The navigation APIs are strictly typed and only allow routes specified in the `pathnames` config. If you need to link to unknown routes in certain places, you can either disable the type checking on a case-by-case basis …

```tsx
// @ts-expect-error
<Link href="/unknown">...</Link>
```

… or globally configure `createLocalizedPathnamesNavigation` to accept arbitrary strings too:

```tsx filename="navigation.ts"
// ...

export const {Link, redirect, usePathname, useRouter} =
  createLocalizedPathnamesNavigation({
    locales,
    pathnames: pathnames as typeof pathnames & Record<string & {}, string>
  });
```

</Details>

</Tab>
</Tabs>

<Details id="link-prefetching">
<summary>How does prefetching of localized links work?</summary>
Just like `next/link`, by default all links are prefetched. The one exception to this is that links to other locales aren't prefetched, because this may result in prematurely overwriting the locale cookie.

</Details>

### `useRouter`

If you need to navigate programmatically, e.g. in an event handler, `next-intl` provides a convience API that wraps [`useRouter` from Next.js](https://nextjs.org/docs/app/api-reference/functions/use-router) and automatically applies the locale of the user.

<Tabs storageKey="pathnames" items={['Shared pathnames', 'Localized pathnames']}>
<Tab>
```tsx
'use client';

import {useRouter} from '../navigation';

const router = useRouter();

// When the user is on `/en`, the router will navigate to `/en/about`
router.push('/about');

// You can override the `locale` to switch to another language
router.replace('/about', {locale: 'de'});

// Dynamic params need to be interpolated into the pathname
router.push('/users/12', {locale: 'de'});

````

<Details id="userouter-change-locale">
<summary>How can I change the locale for the current page?</summary>

By combining [`usePathname`](#usepathname) with [`useRouter`](#userouter), you can change the locale for the current page programmatically.

```tsx
'use client';

import {usePathname, useRouter} from '../navigation';

const pathname = usePathname();
const router = useRouter();

router.replace(pathname, {locale: 'de'});
```

</Details>
</Tab>
<Tab>

When using [localized pathnames](/docs/routing#pathnames), the provided `href` corresponds to an internal pathname, but will be mapped to a locale-specific pathname.

```tsx
'use client';

import {useRouter} from '../navigation';

const router = useRouter();

// When the user is on `/de`, the router will navigate to `/de/ueber-uns`
router.push('/about');

// You can override the `locale` to switch to another language
router.replace('/about', {locale: 'en'});

// Dynamic params need to be provided as objects
router.push({
  pathname: '/users/[userId]',
  params: {userId: '12'}
});

// Search params can be added via `query`
router.push({
  pathname: '/users',
  query: {sortBy: 'name'}
});
````

<Details id="change-locale">
<summary>How can I change the locale for the current page?</summary>

By combining [`usePathname`](#usepathname) with [`useRouter`](#userouter), you can change the locale for the current page programmatically.

Note that if you have dynamic params on some routes, you should pass those as well to potentially resolve an internal pathname.

```tsx
'use client';

import {usePathname, useRouter} from '../navigation';
import {useParams} from 'next/navigation';

const pathname = usePathname();
const router = useRouter();
const params = useParams();

router.replace(
  // @ts-expect-error -- TypeScript will validate that only known `params`
  // are used in combination with a given `pathname`. Since the two will
  // always match for the current route, we can skip runtime checks.
  {pathname, params},
  {locale: 'de'}
);
```

</Details>
</Tab>
</Tabs>

### `usePathname`

To retrieve the pathname without a potential locale prefix, you can call `usePathname`.

<Tabs storageKey="pathnames" items={['Shared pathnames', 'Localized pathnames']}>
<Tab>

```tsx
'use client';

import {usePathname} from '../navigation';

// When the user is on `/en`, this will be `/`
const pathname = usePathname();
```

</Tab>
<Tab>

When using [localized pathnames](/docs/routing#pathnames), the returned pathname will correspond to an internal pathname.

```tsx
'use client';

import {usePathname} from '../navigation';

// When the user is on `/de/ueber-uns`, this will be `/about`
const pathname = usePathname();
```

Note that internal pathnames are returned without params being resolved (e.g. `/users/[userId]`).

</Tab>
</Tabs>

### `redirect`

If you want to interrupt the render and redirect to another page, you can invoke the `redirect` function. This wraps [the `redirect` function from Next.js](https://nextjs.org/docs/app/api-reference/functions/redirect) and automatically applies the current locale.

<Tabs storageKey="pathnames" items={['Shared pathnames', 'Localized pathnames']}>
<Tab>

```tsx
import {redirect} from '../navigation';

// When the user is on `/en`, this will be `/en/login`
redirect('/login');

// Dynamic params need to be interpolated into the pathname
router.push('/users/12');
```

</Tab>
<Tab>

When using [localized pathnames](/docs/routing#pathnames), the provided `href` corresponds to an internal pathname, but will be mapped to a locale-specific pathname.

```tsx
import {redirect} from '../navigation';

// When the user is on `/en`, this will be `/en/login`
redirect('/login');

// Dynamic params need to be provided as objects
redirect({
  pathname: '/help/[articleSlug]',
  params: {articleSlug: 'how-to-login'}
});

// Search params can be added via `query`
redirect({
  pathname: '/users',
  query: {sortBy: 'name'}
});
```

</Tab>
</Tabs>

<Callout>
  [`permanentRedirect`](https://nextjs.org/docs/app/api-reference/functions/permanentRedirect)
  is supported too.
</Callout>

### `getPathname`

If you need to construct a particular pathname based on a locale, you can call the `getPathname` function. This can for example be useful to retrieve a [canonical link](https://nextjs.org/docs/app/api-reference/functions/generate-metadata#alternates) for a page that accepts search params.

<Tabs storageKey="pathnames" items={['Shared pathnames', 'Localized pathnames']}>
<Tab>

(This API is only available for localized pathnames, since it is not necessary for shared pathnames.)

</Tab>
<Tab>

```tsx filename="page.tsx"
import {getPathname} from '../navigation';

export async function generateMetadata({params: {locale}}) {
  // Example: This page accepts search params like `?sort=asc`.
  // A canonical link informs search engines that only the
  // version without search params should be indexed.

  const pathname = getPathname({
    locale,
    href: {
      pathname: '/users/[userId]',
      params: {userId: '5'}
    }
  });

  return {
    alternates: {
      canonical: '/' + locale + pathname
    }
  };
}
```

</Tab>
</Tabs>
